//
//  MainTabbarController.swift
//  EasyDana
//
//  Created by mac on 2024/10/9.
//

import UIKit
import RxSwift
import RxCocoa
class MainTabbarController: UITabBarController {

    let needLogin = PublishSubject<Bool>()
    
    let bag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setValue(MainTabbar(), forKey: "tabBar")
        self.delegate = self
        GlobalNotifier.default.needLogin.bind(to: self.needLogin).disposed(by: self.bag)
        self.needLogin
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] need in
                let loginVC = LoginViewController()
                self?.alert(viewController: loginVC)
            })
            .disposed(by: self.bag)
        self.getCities()
        // Do any additional setup after loading the view.
    }
    
    private func getCities() {
        Task {
            do {
                let res = try await HTTPManager.default.get(path: Api.getCities, param: nil, dataType: [AreaModel].self)
                GlobalNotifier.default.provinces.accept(res.data ?? [])
                let encoder = JSONEncoder()
                let data = try encoder.encode(res.data ?? [])
                let url = URL(fileURLWithPath: NSHomeDirectory() + "provinces.dat", isDirectory: false)
                try data.write(to: url)
            } catch {
                print(error)
            }
        }
    }

}

extension MainTabbarController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let index = tabBarController.viewControllers?.firstIndex(of: viewController) ?? -1
        if index > 0 {
            if HTTPManager.default.sessionID.count == 0 {
                GlobalNotifier.default.needLogin.onNext(true)
                return false
            }
        }
        return true
    }
}
